package com.huang.service.impl;

import com.huang.mapper.CartMapper;
import com.huang.mapper.OrderDetailMapper;
import com.huang.mapper.OrdersMapper;
import com.huang.pojo.Cart;
import com.huang.pojo.OrderDetail;
import com.huang.pojo.Orders;
import com.huang.service.OrdersService;
import com.huang.util.CommonUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class OrdersServiceImpl implements OrdersService {

    @Resource
    private OrdersMapper ordersMapper;
    @Resource
    private CartMapper cartMapper;
    @Resource
    private OrderDetailMapper orderDetailMapper;


    @Override
    public int createOrders(Orders orders) {
        //1,查询当前用户购物车对象中所有商品
        Cart cart = new Cart();
        cart.setUserId(orders.getUserId());
        cart.setBusinessId(orders.getBusinessId());
        List<Cart> cartList = cartMapper.listCart(cart);
        //2,创建订单对象，返回订单编号,并批量添加订单明细
        orders.setOrderDate(CommonUtil.getCurrentDate());
        ordersMapper.saveOrders(orders);
        Integer orderId = orders.getOrderId();
        List<OrderDetail> list = new ArrayList<>();
        for (Cart c : cartList) {
            OrderDetail od = new OrderDetail();
            od.setOrderId(orderId);
            od.setFoodId(c.getFoodId());
            od.setQuantity(c.getQuantity());
            list.add(od);
        }
        orderDetailMapper.saveOrderDetailBatch(list);
        //3,从购物车当中，将所有的商品信息删除
        cartMapper.removeCart(cart);
        return orderId;
    }

    @Override
    public Orders getOrdersById(Integer orderId) {
        return ordersMapper.getOrdersById(orderId);
    }

    @Override
    public List<Orders> listOrdersByUserId(String userId) {
        return ordersMapper.listOrdersByUserId(userId);
    }
}
